<script setup lang="ts">
import {Back} from "@element-plus/icons-vue";
import {useRouter} from "vue-router";
import {onMounted, reactive, ref} from "vue";
import type {collectionInfo, Column} from '@/types'
import api from '@/api/index'
import {ElMessage} from "element-plus";
import type {FormRules} from "element-plus";

const router = useRouter()

let faceColumnList = reactive<Array<Column>>([])

let sampleColumnList = reactive<Array<Column>>([])
const options = ['STRING', 'BOOL', 'DOUBLE', 'FLOAT', 'INT']
const options2 = ['CURR_DB', 'ALI_OSS', 'MIN_IO', 'TCE_COS']


const ruleFormRef = ref()


const collectionInfo = reactive({
  collectionComment: "",
  collectionName: "collect_",
  faceColumns: faceColumnList,
  namespace: "namespace_1",
  replicasNum: 0,
  sampleColumns: sampleColumnList,
  shardsNum: 0,
  storageEngine: "CURR_DB",
  storageFaceInfo: false
})

const faceDataInfo = reactive({
  collectionName: "",
  faceId: "",
  faceImage: "",
  sampleId: ""
})

const regs = {
  // 小写字母、数字和下划线
  name: /^[a-z0-9_]+$/,
  email: /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/,
  number: /^([0]|[1-9][0-9]*)$/,
  password: /^(?=.*\d)(?=.*[a-zA-Z])[\da-zA-Z~!@#$%^&*_]{8,}$/,
  shareCode: /^[A-Za-z0-9]+$/
}
const addColumn = (num: number) => {
  const column = {
    comment: "",
    dataType: "STRING",
    name: ""
  }
  switch (num) {
    case 0:
      sampleColumnList.push(column)
      break;
    case 1:
      faceColumnList.push(column)
      break;
  }
}


const deleteColumn = (num: number) => {
  switch (num) {
    case 0:
      sampleColumnList.length > 1 ? sampleColumnList.pop() : ElMessage.error('至少保留一条数据！')
      break;
    case 1:
      faceColumnList.length > 1 ? faceColumnList.pop() : ElMessage.error('至少保留一条数据')

      break;
  }
}

const verify = (rule: any, value: any, callback: any) => {
  if (callback != null) {
    for (let i = 0; i < value.length; i++) {
      let data = value[i]
      let note = '[' + i + ']'
      if (data.name.trim().length < 1 || data.name.trim().length > 32 || !regs.name.test(data.name.trim())) {
        callback(new Error(note + '.name 请输入1-32位的字母、数字和下划线'))
        return
      }
      if (data.comment.trim().length < 1 || data.comment.trim().length > 64) {
        callback(new Error(note + '.comment 请输入1-64位的字符'))
        return
      }
    }
  } else {
    let a = true
    Object.keys(collectionInfo).forEach((item) => {
      if (item === 'sampleColumns' || item === 'faceColumns') {
        for (let i = 0; i < collectionInfo[item].length; i++) {
          let note = 'sampleColumns[' + i + ']'
          if (collectionInfo[item][i].name.trim() === '' || collectionInfo[item][i].name === null) {
            ElMessage.error(note + '.name 请输入1-32位的字母、数字和下划线')
            a = false
          } else if (collectionInfo[item][i].dataType.trim() === '' || collectionInfo[item][i].dataType === null) {
            ElMessage.error('请完成表单信息！请输入' + item + '[' + i + '].dataType')
            a = false
          } else if (collectionInfo[item][i].comment.trim() === '' || collectionInfo[item][i].comment === null) {
            ElMessage.error(note + '.comment 请输入1-64位的字符')
            a = false
          }
        }
      } else if (collectionInfo[item] === '' || collectionInfo[item] === null) {
        ElMessage.error('请完成表单信息！请输入' + item)
        a = false
      }
    })
    return a
  }
}


const addCcollection = () => {
  if (verify(null, null, null)) {
    api.addCollection(collectionInfo)
        .then(res => {
          if (res.data.code === 0) {
            ElMessage.success(res.data.message)
            router.push('/collection')
          } else {
            ElMessage.error(res.data.message)
          }
        })
  }
}

const rules = reactive<FormRules<typeof collectionInfo>>({
  namespace: [
    {required: true, message: '请输入命名空间', trigger: 'blur'},
    {min: 1, max: 12, message: '长度在 1到 12 个字符', trigger: 'blur'},
    {pattern: regs.name, message: "请输入正确的格式，支持小写字母、数字和下划线", trigger: "blur"},
  ],
  collectionName: [
    {required: true, message: '请输入集合名称', trigger: 'blur'},
    {min: 1, max: 24, message: '长度在 1到 24 个字符', trigger: 'blur'},
    {pattern: regs.name, message: "请输入正确的格式，支持小写字母、数字和下划线", trigger: "blur"},
  ],
  collectionComment: [
    {required: true, message: '请输入集合描述', trigger: 'blur'},
    {min: 1, max: 128, message: '长度在 1 到 128 个字符', trigger: 'blur'}
  ],
  storageEngine: [
    {required: true, message: '请输入存储引擎', trigger: 'blur'},
    {min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur'}
  ],
  storageFaceInfo: [
    {required: true, message: '请输入存储人脸信息', trigger: 'blur'},
  ],
  sampleColumns: [
    {required: true, message: '请输入样本扩展字段信息', trigger: 'blur'},
    {validator: verify}
  ],
  shardsNum: [
    {required: true, message: '请输入集合分片数量', trigger: 'blur'},
    {pattern: regs.number, message: "请输入正确的格式，支持小写字母、数字和下划线", trigger: "blur"},
  ],
  replicasNum: [
    {required: true, message: '请输入数据分片最大文件个数', trigger: 'blur'},
    {pattern: regs.number, message: "请输入正确的格式，支持小写字母、数字和下划线", trigger: "blur"},
  ],
  faceColumns: [
    {required: true, message: '请输入信息', trigger: 'blur'},
    {validator: verify}
  ]
})


onMounted(() => {
  addColumn(0)
  addColumn(1)
})

</script>

<template>
  <el-button type="primary" :icon="Back" @click="router.back()">返回</el-button>
  <el-form :model="collectionInfo" label-width="auto" :rules="rules" ref="ruleFormRef" style="max-width: 100%">
    <el-form-item label="namespace（命名空间）：" prop="namespace">
      <el-input v-model="collectionInfo.namespace"/>
    </el-form-item>
    <el-form-item label="collectionName（集合名称）：" prop="collectionName">
      <el-input v-model="collectionInfo.collectionName"/>
    </el-form-item>
    <el-form-item label="collectionComment（集合描述）：" prop="collectionComment">
      <el-input v-model="collectionInfo.collectionComment"/>
    </el-form-item>
    <el-form-item label="sampleColumns（自定义的样本属性字段）：" prop="sampleColumns">
      <div v-for="(item,index) in sampleColumnList" :key="index" class="flex gap-4 mb-4">
        name:&nbsp;<el-input v-model="item.name" placeholder="请输入字段名称" style="width: 150px"/>&nbsp;
        comment:&nbsp;<el-input v-model="item.comment" placeholder="请输入字段描述" style="width: 150px"/>&nbsp;
        dataType:&nbsp;
        <el-select v-model="item.dataType" placeholder="Select" style="width: 150px">
          <el-option
              v-for="item in options"
              :key="item"
              :label="item"
              :value="item"
          />
        </el-select>&nbsp;
      </div>
      <div>
        <el-button type="primary" @click="addColumn(0)">添加</el-button>
        <el-button type="primary" @click="deleteColumn(0)">删除</el-button>
      </div>
    </el-form-item>

    <el-form-item label="faceColumns（自定义的人脸属性字段）：" prop="faceColumns">
      <div v-for="(item,index) in faceColumnList" :key="index" class="flex gap-4 mb-4">
        name:&nbsp;<el-input v-model="item.name" placeholder="请输入字段名称" style="width: 150px"/>&nbsp;
        comment:&nbsp;<el-input v-model="item.comment" placeholder="请输入字段描述" style="width: 150px"/>&nbsp;
        dataType:&nbsp;
        <el-select v-model="item.dataType" placeholder="Select" style="width: 150px">
          <el-option
              v-for="item in options"
              :key="item"
              :label="item"
              :value="item"
          />
        </el-select>&nbsp;
      </div>
      <el-button type="primary" @click="addColumn(1)">添加</el-button>
      <el-button type="primary" @click="deleteColumn(1)">删除</el-button>

    </el-form-item>
    <el-form-item label="replicasNum（数据分片中最大的文件个数）：" prop="replicasNum">
      <el-input v-model="collectionInfo.replicasNum" placeholder="默认为0,仅对Proxima引擎生效"/>
    </el-form-item>
    <el-form-item label="shardsNum（要创建的集合的分片个数）：" prop="shardsNum">
      <el-input v-model="collectionInfo.shardsNum" placeholder="默认为0,仅对Milvus引擎生效"/>
    </el-form-item>
    <el-form-item label="storageEngine（存储引擎）：" prop="storageEngine">
      <el-select v-model="collectionInfo.storageEngine" placeholder="Select" style="width: 150px">
        <el-option
            v-for="item in options2"
            :key="item"
            :label="item"
            :value="item"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="storageFaceInfo（存储人脸信息）：" prop="storageFaceInfo">
      <el-radio-group v-model="collectionInfo.storageFaceInfo">
        <el-radio :value='true' border>true</el-radio>
        <el-radio :value='false' border>false</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-button type="primary" @click="addCcollection" style="width: 50%;font-size: 20px;margin-left: 25%">
      创建
    </el-button>
  </el-form>

</template>

<style scoped>

</style>